package com.whcoding.test.common.encrypt;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @program: spring-boot-learning
 * @description: 计算签名
 * @author: whcoding
 * @create: 2022-05-25 14:00
 **/
public class SignatureUtils {
	/**
	 * 计算签名
	 * @param paramsMap
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String signature(Map<String, String> paramsMap)
			throws UnsupportedEncodingException {
		List<String> list = new ArrayList<>();
		for (Map.Entry<String, String> element : paramsMap.entrySet()) {
			list.add(concatParamStr(element.getKey(), element.getValue()));
		}
		StringBuilder sb = new StringBuilder();
		Collections.sort(list);
		for (String sigParam : list) {
			sb.append(sigParam);
		}
		return DigestUtils.sha256Hex(sb.toString().
				getBytes(StandardCharsets.UTF_8.name()));
	}

	/**
	 * 参数拼接
	 * @param key
	 * @param value
	 * @return
	 */
	private static String concatParamStr(String key, String value) {
		return key.concat("=").concat(value);
	}


	/**
	 * map转str
	 *
	 * @param map
	 * @return
	 */
	public static String getMapToString(Map<String, String> map) {
		Set<String> keySet = map.keySet();
		//将set集合转换为数组
		String[] keyArray = keySet.toArray(new String[keySet.size()]);
		//给数组排序(升序)
		Arrays.sort(keyArray);
		//因为String拼接效率会很低的，所以转用StringBuilder。
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < keyArray.length; i++) {
			// 参数值为空，则不参与签名 这个方法trim()是去空格
			if (map.get(keyArray[i]).trim().length() > 0) {
				sb.append(keyArray[i]).append("=").append(map.get(keyArray[i]).trim());
			}
			if (i != keyArray.length - 1) {
				sb.append("&");
			}
		}
		return sb.toString();
	}

}
